import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:magic_car/baoxiu/enusuranceinspector.dart';
import 'package:magic_car/common/nodata.dart';
import 'package:magic_car/jiance/inspectstart.dart';
import 'package:magic_car/jiance/insurance.dart';
import 'package:magic_car/jiance/jiance_detail.dart';
// import 'package:magic_car/res/colors.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/colors.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:toast/toast.dart';

class EnsuranceListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new OrderActState();
  }
}

class OrderActState extends State<EnsuranceListPage>
    with SingleTickerProviderStateMixin {
  List<Choice> _tabs = [];
  TabController mTabController;
  ScrollController _scrollController = new ScrollController();
  int mCurrentPosition = 0;
  List orders = [];
  int type = 0;
  int page = 1;

  @override
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        titleSpacing: 0,
        title: new Text(
          '保修订单',
          style: TextStyle(fontSize: Config.title_size),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        bottom: new TabBar(
          indicatorSize: TabBarIndicatorSize.label,
          indicatorColor: Colours.app_main,
          labelColor: Colours.app_main,
          unselectedLabelColor: Colors.black45,
          tabs: _tabs.map((Choice choice) {
            return new Tab(
              text: choice.title,
            );
          }).toList(),
          controller: mTabController,
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      floatingActionButton: FloatingActionButton(
        mini: false,
        onPressed: () {
          Navigator.pushNamed(context, "ensurancestart");
        },
        child: Center(
          child: Text(
            '新增',
            style: TextStyle(color: Colors.white),
          ),
        ),
        // child: Icon(
        //   Icons.add,
        //   color: Colors.white,
        // ),
        backgroundColor: Colours.bj_orange_o2,
      ),
      body: new TabBarView(
        children: _tabs.map((Choice choice) {
          return new Padding(
              padding: const EdgeInsets.all(0.0),
              child: new Container(
                  child: orders.length == 0
                      ? Nodata()
                      : new ListView(
                          controller: _scrollController,
                          children: <Widget>[buildcontent()],
                        )));
        }).toList(),
        controller: mTabController,
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _tabs.add(Choice(title: '待处理', position: 0));
    _tabs.add(Choice(title: '进行中', position: 1));

    _tabs.add(Choice(title: '已完成', position: 2));

    mTabController =
        new TabController(length: _tabs.length, vsync: ScrollableState());
    //判断TabBar是否切换
    mTabController.addListener(() {
      if (mTabController.index == mCurrentPosition) return;
      print('滑动监听' + mTabController.index.toString());
      setState(() {
        page = 1;
        type = mTabController.index;

        mCurrentPosition = mTabController.index;
      });
      loaddata(); //滑动时加载数据
    });
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        print("滑动到底部");
      }
    });
    loaddata();
  }

  //加载数据
  loaddata() async {
    EasyLoading.showToast("加载中。。。");
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["uid"] = pref.getString('uid');
    map["page"] = page.toString();
    map['status'] = type.toString();
    print(map);

    HttpHelper.post(HttpHelper.API_EnsuranceCarlist, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          if (this.page == 1) {
            orders.clear();
            setState(() {
              orders = [];
            });
          }

          Future.delayed(Duration(seconds: 2), () {
            EasyLoading.dismiss(); //延时动画加更新，防止数据重复
            orders.addAll(data["info"]);
            setState(() {
              orders = orders;
            });
          });

          if (data['info'].length == 10) {
            setState(() {
              page = page + 1;
            });
          }
          //pref.setStringList('userinfo', data["info"]);

        } else {
          EasyLoading.dismiss();
        }
      } else {
        EasyLoading.dismiss();
      }
    }, params: map);
  }

  @override
  void dispose() {
    super.dispose();
    mTabController.dispose();
  }

  Widget buildcontent() {
    print('重新绘制');
    List<Widget> tiles = [];
    Widget content;
    for (var item in orders) {
      tiles.add(
        InkWell(
            onTap: () {
              if (item['is_canensurance'].toString() == "1" &&
                  item['order_id'].toString() != "0") {
                if (item['order_info']['is_start'].toString() == "1") {
                  //进入到检测页面
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new InsurancePapularinspects(
                        item['order_info']['id'].toString(), 1, {}, false);
                  })).then((param) {});
                } else {
                  //进入到人车合照
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new StartPicPage(
                        item['order_info']['id'].toString(), "保修检测");
                  })).then((param) {});
                }
              } else {
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return new EnsuranceOBDPage(item['id']);
                })).then((param) {});
              }
            },
            child: Container(
                width: double.infinity - 20,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                padding: EdgeInsets.all(10),
                margin: EdgeInsets.fromLTRB(10, 5, 10, 5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "车架：${item['vin']}",
                      style: TextStyle(fontWeight: FontWeight.w600),
                    ),
                    Container(
                      height: 5,
                    ),
                    Text("商家：${item['bussiness_name']}"),
                    Container(
                      height: 5,
                    ),
                    Text(
                      "状态：${item['status_str']}",
                      style: TextStyle(color: Colours.bj_red_r1),
                    ),
                    Container(
                      height: 5,
                    ),
                    Text(
                      "结果：${item['ensurance_str']}",
                      style: TextStyle(color: Colours.bj_red_r2),
                    ),
                    Container(
                      height: 5,
                    ),
                    item.containsKey('order_info')
                        ? Text(
                            '品牌：${item['order_info']['brand_string']['name']}/${item['order_info']['cartype_string']['name']}')
                        : Text("品牌：无"),
                    Container(
                      height: item.containsKey('order_info') ? 5 : 5,
                    ),
                    Text(
                      "${item['create_time']}",
                      style: TextStyle(fontSize: 12),
                    ),
                  ],
                ))),
      );
      // tiles.add(
      //   Container(
      //     width: double.infinity-20,
      //     decoration: BoxDecoration(
      //       color: Colors.white,
      //       borderRadius: BorderRadius.all(Radius.circular(10))
      //     ),
      //     padding: EdgeInsets.all(10),
      //     margin: EdgeInsets.fromLTRB(10, 5, 10, 5),
      //   child: Text('车架号：${item['vin']}'),
      // ));
    }
    content = new Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }
}

//   Widget buildcontent() {
//     List<Widget> tiles = [];
//     Widget content;
//     for (var i = 0; i < orders.length; i++) {
//       var order = orders[i];
//       tiles.add(Padding(
//           padding: new EdgeInsets.fromLTRB(15, 10, 15, 0),
//           child: Container(
//             decoration: new BoxDecoration(
//               color: Colors.white,
//             ),
//             child: Column(
//               children: <Widget>[
//                 Padding(
//                   padding: new EdgeInsets.fromLTRB(20, 10, 20, 10),
//                   child: Row(
//                     children: <Widget>[
//                       Expanded(
//                           flex: 2,
//                           child: new Text(
//                             order["order_sn"],
//                             style: TextStyle(
//                                 color: Color.fromRGBO(51, 51, 51, 1),
//                                 fontSize: 13),
//                           )),
//                       Expanded(
//                         flex: 1,
//                         child: new Align(
//                             alignment: Alignment.centerRight,
//                             child: Container(
//                                 padding: new EdgeInsets.fromLTRB(5, 2, 5, 2),
//                                 color: Colours.app_main,
//                                 child: new Text(
//                                   order["test_type"],
//                                   style: TextStyle(
//                                       color: Colors.white, fontSize: 12),
//                                 ))),
//                       )
//                     ],
//                   ),
//                 ),
//                 Padding(
//                   padding: new EdgeInsets.fromLTRB(20, 10, 20, 10),
//                   child: Row(
//                     children: <Widget>[
//                       Expanded(
//                           flex: 1,
//                           child: new Text(
//                             '联系电话',
//                             style: TextStyle(
//                                 fontSize: 12,
//                                 color: Color.fromRGBO(51, 51, 51, 1)),
//                           )),
//                       Expanded(
//                         flex: 1,
//                         child: new Align(
//                             alignment: Alignment.centerRight,
//                             child: Container(
//                                 child: new Text(
//                               order["phone_num"],
//                               style: TextStyle(
//                                   color: Color.fromRGBO(153, 153, 153, 1),
//                                   fontSize: 12),
//                             ))),
//                       )
//                     ],
//                   ),
//                 ),
//                 Padding(
//                   padding: new EdgeInsets.fromLTRB(20, 0, 20, 10),
//                   child: Row(
//                     children: <Widget>[
//                       Expanded(
//                           flex: 1,
//                           child: new Text(
//                             '预约时间',
//                             style: TextStyle(
//                                 fontSize: 12,
//                                 color: Color.fromRGBO(51, 51, 51, 1)),
//                           )),
//                       Expanded(
//                         flex: 1,
//                         child: new Align(
//                             alignment: Alignment.centerRight,
//                             child: Container(
//                                 child: new Text(
//                               order["order_time"],
//                               style: TextStyle(
//                                   color: Color.fromRGBO(153, 153, 153, 1),
//                                   fontSize: 12),
//                             ))),
//                       )
//                     ],
//                   ),
//                 ),
//                 Padding(
//                   padding: new EdgeInsets.fromLTRB(20, 0, 20, 10),
//                   child: Row(
//                     children: <Widget>[
//                       Expanded(
//                           flex: 1,
//                           child: new Text(
//                             '订单金额',
//                             style: TextStyle(
//                                 fontSize: 12,
//                                 color: Color.fromRGBO(51, 51, 51, 1)),
//                           )),
//                       Expanded(
//                         flex: 1,
//                         child: new Align(
//                             alignment: Alignment.centerRight,
//                             child: Container(
//                                 child: new Text(
//                               order['orderPrice'],
//                               style: TextStyle(
//                                   color: Color.fromRGBO(251, 73, 57, 1),
//                                   fontSize: 12),
//                             ))),
//                       )
//                     ],
//                   ),
//                 ),
//                 Padding(
//                   padding: new EdgeInsets.fromLTRB(20, 0, 20, 10),
//                   child: Row(
//                     children: <Widget>[
//                       Expanded(
//                           flex: 1,
//                           child: new Text(
//                             '汽车品牌',
//                             style: TextStyle(
//                                 fontSize: 12,
//                                 color: Color.fromRGBO(51, 51, 51, 1)),
//                           )),
//                       Expanded(
//                         flex: 1,
//                         child: new Align(
//                             alignment: Alignment.centerRight,
//                             child: Container(
//                                 child: new Text(
//                               order["brand_string"]["name"],
//                               style: TextStyle(
//                                   color: Color.fromRGBO(153, 153, 153, 1),
//                                   fontSize: 12),
//                             ))),
//                       )
//                     ],
//                   ),
//                 ),
//                 Padding(
//                   padding: new EdgeInsets.fromLTRB(20, 10, 20, 10),
//                   child: Align(
//                       alignment: Alignment.centerRight,
//                       child: new Container(
//                         child: new Material(
//                           //INK可以实现装饰容器
//                           child: new Ink(
//                             //用ink圆角矩形
//                             // color: Colors.red,
//                             decoration: new BoxDecoration(
//                               //背景
//                               color: Colors.white,
//                               //设置四周圆角 角度
//                               borderRadius:
//                                   BorderRadius.all(Radius.circular(15.0)),
//                               //设置四周边框
//                               border: new Border.all(
//                                 width: 1,
//                                 color: Colours.app_main,
//                               ),
//                             ),
//                             child: new InkWell(
//                                 //圆角设置,给水波纹也设置同样的圆角
//                                 //如果这里不设置就会出现矩形的水波纹效果
//                                 borderRadius: new BorderRadius.circular(15.0),
//                                 //设置点击事件回调
//                                 onTap: () {
//                                   print(order["id"].toString());
//                                   // Navigator.pushNamed(context, 'jianceorder_detail');
//                                   Navigator.of(context)
//                                       .push(new MaterialPageRoute(builder: (_) {
//                                     return new JIanceDetailPage(
//                                         order["id"].toString());
//                                   }));
//                                 },
//                                 child: Container(
//                                   //设置 child 居中
//                                   alignment: Alignment(0, 0),
//                                   height: 30,
//                                   width: 85,
//                                   child: Text(
//                                     "查看订单",
//                                     style: TextStyle(
//                                       color: Colours.app_main,
//                                     ),
//                                   ),
//                                 )),
//                           ),
//                         ),
//                       )
//                       // child: new RaisedButton(
//                       //   child: Text('申请补考'),
//                       //   onPressed: () {},
//                       // ),
//                       ),
//                 ),
//               ],
//             ),
//           )));
//     }
//     content = new Column(
//         children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
//         //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
//         );
//     return content;
//   }
// }

Widget buttons() {
  Widget button = Container(
    margin: EdgeInsets.only(left: 40, top: 40),
    child: new Material(
      //INK可以实现装饰容器
      child: new Ink(
        //用ink圆角矩形
        // color: Colors.red,
        decoration: new BoxDecoration(
          //背景
          color: Colors.white,
          //设置四周圆角 角度
          borderRadius: BorderRadius.all(Radius.circular(25.0)),
          //设置四周边框
          border: new Border.all(width: 1, color: Colors.red),
        ),
        child: new InkWell(
            //圆角设置,给水波纹也设置同样的圆角
            //如果这里不设置就会出现矩形的水波纹效果
            borderRadius: new BorderRadius.circular(25.0),
            //设置点击事件回调
            onTap: () {},
            child: Container(
              //设置 child 居中
              alignment: Alignment(0, 0),
              height: 50,
              width: 300,
              child: Text("点击 Container 圆角边框"),
            )),
      ),
    ),
  );
  return button;
}

class Choice {
  const Choice({this.title, this.icon, this.position});
  final String title;
  final int position;
  final IconData icon;
}
